/**
 * Created by yiihua-013 on 16/10/26.
 *
 * 分布式取余算法
 */

'use strict';

const util = require('util')

var Hash = require('./hash')

function Mod() {
    this.nodes = [];
}

util.inherits(Mod, Hash)

// var ret = new Mod().hash('1223')
// console.log(ret)

var fn = Mod.prototype;

fn.lookup = function (key) {
    var pos = this.hash(key) % this.nodes.length;
    return this.nodes[pos];
};

fn.addNode = function (node) {
    if (!~this.nodes.indexOf(node)) this.nodes.push(node);
};

fn.deleteNode = function (node) {
    var index = this.nodes.indexOf(node);
    if (~index) this.nodes.splice(index, 1);
};

// var mod = new Mod();
// mod.addNode('192.168.1.1')
// mod.addNode('192.168.1.1')
// mod.addNode('192.168.1.2')
// mod.addNode('192.168.1.3')
//
// var key = 'name';
// console.log(`key ${key}的落点为${mod.hash(key)},所在服务器为:${mod.lookup(key)}`)
// key = "sex";
// console.log(`key ${key}的落点为${mod.hash(key)},所在服务器为:${mod.lookup(key)}`)

module.exports = Mod
